﻿using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using Hiver.Util.Config;
using Hiver.Util.Config.Model;

namespace Hiver.Util.RabbitMQ
{
    /// <summary>
    /// RabbitMQ帮助类
    /// </summary>
    public class RabbitHelper
    {
        /// <summary>
        /// RabbitMQ工厂实例
        /// </summary>
        private ConnectionFactory factory;

        /// <summary>
        /// 是否持久化
        /// </summary>
        private bool durable = true;

        /// <summary>
        /// 构造函数
        /// </summary>
        public RabbitHelper()
        {
            ApplicationConfigModel config = YamlHelper<ApplicationConfigModel>.Load();
            if (config == null)
                Error.Show(1);
            if (config.Rabbitmq == null)
                Error.Show(8);
            factory = new ConnectionFactory()
            {
                HostName = config.Rabbitmq.Host,
                UserName = config.Rabbitmq.Username,
                Password = config.Rabbitmq.Password
            };
            durable = config.Rabbitmq.Persistent;
        }

        /// <summary>
        /// 发送普通消息
        /// </summary>
        /// <param name="queueName"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public void SendMessage(string queueName, string message)
        {
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queueName, durable, false, false, null);
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = durable;
                    channel.BasicPublish("", queueName, properties, Encoding.UTF8.GetBytes(message));
                }
            }
        }

        /// <summary>
        /// 发送Json消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queueName"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public void SendJsonMessage<T>(string queueName, T model)
        {
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queueName, durable, false, false, null);
                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = durable;
                    string json = JsonConvert.SerializeObject(model);
                    channel.BasicPublish("", queueName, properties, Encoding.UTF8.GetBytes(json));
                }
            }
        }
    }
}